package com.example.config.shiro;

import com.example.bean.shiro.ResponseBean;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/7/26 9:52
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
@RestControllerAdvice(basePackages = {"com.example.shiro.controller"})
public class GlobalException {
    @ExceptionHandler(RuntimeException.class)
    public ResponseBean handlerRuntimeExcepetion(HandlerMethod handlerMethod,Exception e) {
        Exception exception = (Exception) e;
        Map<String,Object> map=new HashMap<>();
        map.put("className", handlerMethod.getBean().getClass());
        map.put("methodName", handlerMethod.getMethod().getName());
        return new ResponseBean(HttpStatus.BAD_REQUEST.value(), exception.getMessage(), map);
    }


    @ExceptionHandler(Exception.class)
    public ResponseBean handlerExcepetion(Exception e) {
        Exception exception = (Exception) e;
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        if (e instanceof NoHandlerFoundException) {
            status = HttpStatus.NOT_FOUND.value();
        }
        return new ResponseBean(status, exception.getMessage(), null);
    }

    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    public ResponseBean handleAuthorizationException(AuthorizationException e){
        return new ResponseBean(403,"没有权限，请联系管理员授权", null);
    }


    @ExceptionHandler(PoolException.class)
    public ResponseBean handlePoolException(PoolException e) {
        return new ResponseBean(500,"redis连接异常", e.getMessage());
    }

}
